package com.yunquan.ohana.ui.calendar

import android.app.Application
import android.os.Bundle
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import androidx.lifecycle.LifecycleOwner
import com.google.gson.Gson
import com.yunquan.ohana.BR
import com.yunquan.ohana.R
import com.yunquan.ohana.base.binding.command.BindingAction
import com.yunquan.ohana.base.binding.command.BindingCommand
import com.yunquan.ohana.base.ui.BaseViewModel
import com.yunquan.ohana.entity.HomeInformationModel
import com.yunquan.ohana.entity.UserManager
import com.yunquan.ohana.http.BaseHttp
import com.yunquan.ohana.http.observer.BaseObserver
import com.yunquan.ohana.http.transformer.CommonTransformer
import com.yunquan.ohana.ui.calendar.event.EventActivity
import com.yunquan.ohana.ui.calendar.lists.ListsActivity
import com.yunquan.ohana.ui.calendar.profiles.ProfilesActivity
import com.yunquan.ohana.ui.calendar.profiles.list.ProfilesListActivity
import com.yunquan.ohana.ui.calendar.sync.SyncActivity
import com.yunquan.ohana.ui.calendar.task.TaskActivity
import com.yunquan.ohana.utils.DateUtils
import com.yunquan.ohana.utils.L
import com.yunquan.ohana.utils.SPUtils
import com.yunquan.ohana.utils.ToastUtils
import com.yunquan.ohana.utils.Utils
import io.reactivex.rxjava3.disposables.Disposable
import me.tatarka.bindingcollectionadapter2.ItemBinding
import okhttp3.RequestBody.Companion.toRequestBody

class CalendarMenuViewModel(application: Application) : BaseViewModel(application) {

    val title = ObservableField<String>()
    val today = ObservableField<String>()
    val todayEventTip = ObservableField<String>()
    val eventTip = ObservableField<String>()
    val taskTip = ObservableField<String>()
    val listsTip = ObservableField<String>()
    val profilesTip = ObservableField<String>()

    val eventItems = ObservableArrayList<EventItemViewModel<CalendarMenuViewModel>>()
    val eventItemBinding = ItemBinding.of<EventItemViewModel<CalendarMenuViewModel>>(
        BR.eventItemViewModel,
        R.layout.item_schedule
    )

    var mDeviceId: String? = null
    var mData: HomeInformationModel? = null

    val onEventClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            val bundle = Bundle()
            bundle.putString("deviceId", mDeviceId)
            bundle.putBoolean("userType", mData?.userType == 1)
            startActivity(EventActivity::class.java, bundle)
        }
    })

    val onTaskClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            val bundle = Bundle()
            bundle.putString("deviceId", mDeviceId)
            bundle.putBoolean("userType", mData?.userType == 1)
            bundle.putString("roleId", mData?.roleId)
            startActivity(TaskActivity::class.java, bundle)
        }
    })

    val onListsClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            val bundle = Bundle()
            bundle.putString("deviceId", mDeviceId)
            bundle.putBoolean("userType", mData?.userType == 1)
            startActivity(ListsActivity::class.java, bundle)
        }
    })

    val onProfilesClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            val isProfiles = SPUtils.getBoolean("isProfiles_${UserManager.instance.getUser()?.id}_${mDeviceId}", false)
            val bundle = Bundle()
            bundle.putString("deviceId", mDeviceId)
            bundle.putBoolean("userType", mData?.userType == 1)
            if (isProfiles) {
                startActivity(ProfilesListActivity::class.java, bundle)
            } else {
                startActivity(ProfilesActivity::class.java, bundle)
            }
        }
    })

    val onSyncClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            val bundle = Bundle()
            bundle.putString("deviceId", mDeviceId)
            bundle.putString("roleId", mData?.roleId)
            startActivityResult(SyncActivity::class.java, bundle)
        }
    })

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        today.set(DateUtils.now("EEEE, MMMM d"))
        todayEventTip.set(Utils.instance.getString(R.string.no_upcoming_events_day))
        homeInformation()
    }

    private fun homeInformation() {
        if (mDeviceId == null) {
            ToastUtils.showShort("Please select device")
            L.d("mDeviceId 为空")
            return
        }
        val params = mutableMapOf<String, Any>()
        params["deviceId"] = mDeviceId!!
        val body = Gson().toJson(params).toRequestBody(BaseHttp.MEDIA_TYPE_JSON)
        BaseHttp.api.homeInformation(body)
            .compose(CommonTransformer())
            .subscribe(object : BaseObserver<HomeInformationModel>() {
                override fun onSubscribe(d: Disposable) {
                    super.onSubscribe(d)
                    showLoading()
                }

                override fun onSuccess(result: HomeInformationModel?) {
                    super.onSuccess(result)
                    mData = result
                    eventItems.clear()
                    // 顶部日历
                    val schedules = result?.schedules ?: mutableListOf()
                    val subList = if (schedules.size > 2) {
                        schedules.subList(0, 2)
                    } else {
                        schedules
                    }
                    subList.forEach {
                        eventItems.add(EventItemViewModel(this@CalendarMenuViewModel, it))
                    }
                    // 初始化 Calendar 描述
                    todayEventTip.set(
                        if (result?.schedules?.isNotEmpty() == true) {
                            Utils.instance.context.getString(R.string.your_upcoming_events)
                        } else {
                            Utils.instance.context.getString(R.string.no_upcoming_events_day)
                        }
                    )
                    // 初始化 Event 描述
                    eventTip.set(
                        if (result?.schedules?.isNotEmpty() == true) {
                            Utils.instance.context.getString(R.string.events_today, result.schedules?.size)
                        } else {
                            Utils.instance.context.getString(R.string.no_events_today)
                        }
                    )
                    // 初始化 Task 描述
                    taskTip.set(
                        if ((result?.taskCount ?: 0) > 0) {
                            Utils.instance.context.getString(R.string.task_today, result!!.taskCount)
                        } else {
                            Utils.instance.context.getString(R.string.all_done_for_today)
                        }
                    )
                    // 初始化 Lists 描述
                    listsTip.set(Utils.instance.context.getString(R.string.lists_format, result?.listCount ?: 0))
                    // 初始化 Profiles 描述
                    val profileCount = result?.profilesCount ?: 0
                    val profileMaxCount = result?.profilesMaxCount ?: 0
                    val reduceCount = profileMaxCount - profileCount
                    profilesTip.set(
                        if (reduceCount > 0) {
                            if (profileCount > 0) {
                                Utils.instance.context.getString(
                                    R.string.profiles_format,
                                    profileCount, reduceCount
                                )
                            } else {
                                Utils.instance.context.getString(R.string.no_profiles)
                            }
                        } else {
                            Utils.instance.context.getString(R.string.profiles_desc_format, profileCount)
                        }
                    )
                }

                override fun onComplete() {
                    super.onComplete()
                    hideLoading()
                }
            })
    }
}